from business import Business
from handler import MyAPIHandler
import cv2
import numpy as np
from datetime import datetime as dt


def upload_img(image, business:Business):
    image = image[0]
    ext = image['filename']
    ext = ext[ext.rfind('.') + 1:]
    image = image['body']

    cache_id = business.save_to_cache(image)
    return {'cache_id': cache_id, 'ext': ext}


def download_img(cache_id, ext, business:Business, handler: MyAPIHandler):
    img = business.get_from_cache(cache_id)
    handler.json_response = False
    handler.set_header('Content-Type', 'image/%s' % ext)
    handler.write(img)


def detect_img(cache_id, business:Business):
    img = _get_image(cache_id, business)
    return business.detect_img(img)


def save_img(cache_id, camera_id:int, business: Business):
    img = _get_image(cache_id, business)
    return business.save_img(camera_id, img, dt.now())


def _get_image(cache_id, business):
    img = business.get_from_cache(cache_id)
    img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_COLOR)
    h, w, _ = img.shape
    img = cv2.resize(img, (w // 2, h // 2))
    return img
